from vnpy_ctastrategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)
from vnpy.trader.constant import Status


class DoubleMaStrategy(CtaTemplate):
    """"""

    author = "用Python的交易员"

    fast_window: int = 10
    slow_window: int = 20

    fast_ma0: float = 0.0
    fast_ma1: float = 0.0
    slow_ma0: float = 0.0
    slow_ma1: float = 0.0

    parameters = ["fast_window", "slow_window"]
    variables = ["fast_ma0", "fast_ma1", "slow_ma0", "slow_ma1"]

    def on_init(self) -> None:
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")

        self.bg: BarGenerator = BarGenerator(self.on_bar)
        self.am: ArrayManager = ArrayManager()

        self.load_bar(10)

    def on_start(self) -> None:
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")
        self.put_event()

    def on_stop(self) -> None:
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

        self.put_event()

    def on_tick(self, tick: TickData) -> None:
        """
        Callback of new tick data update.
        """
        self.write_log(f"📥 策略收到Tick数据: {tick.vt_symbol} 时间={tick.datetime} 价格={tick.last_price} 量={tick.volume}")
        self.bg.update_tick(tick)
        self.write_log(f"🔄 Tick数据已发送给BarGenerator处理")

    def on_bar(self, bar: BarData) -> None:
        """
        Callback of new bar data update.
        """
        self.write_log(f"📊 策略收到Bar数据: {bar.vt_symbol} 时间={bar.datetime} 开={bar.open_price} 高={bar.high_price} 低={bar.low_price} 收={bar.close_price} 量={bar.volume}")
        
        self.cancel_all()

        am: ArrayManager = self.am
        am.update_bar(bar)
        self.write_log(f"📈 技术指标更新: 当前K线数={am.count} 均线周期={self.fast_window}/{self.slow_window}")
        
        if not am.inited:
            self.write_log("⏳ 技术指标未初始化完成")
            return

        fast_ma = am.sma(self.fast_window, array=False)
        self.fast_ma0 = float(fast_ma)
        
        slow_ma = am.sma(self.slow_window, array=False)
        self.slow_ma0 = float(slow_ma)

        cross_over: bool = (self.fast_ma0 > self.slow_ma0 and 
                            self.fast_ma1 < self.slow_ma1)
        cross_below: bool = (self.fast_ma0 < self.slow_ma0 and 
                             self.fast_ma1 > self.slow_ma1)
        
        self.write_log(f"📉 均线计算: 快线={self.fast_ma0:.2f} 慢线={self.slow_ma0:.2f} 上穿={cross_over} 下穿={cross_below}")

        # Use a more meaningful order size instead of fixed 1 share
        order_size = 100  # Default to 100 shares
        
        if cross_over:
            self.write_log("🟢 金叉信号: 快线上穿慢线")
            if self.pos == 0:
                self.write_log(f"💰 准备买入开仓: 价格={bar.close_price}, 数量={order_size}")
                order_id = self.buy(bar.close_price, order_size)
                self.write_log(f"💰 执行买入开仓: 订单ID={order_id}")
            elif self.pos < 0:
                self.write_log(f"💰 准备买入平仓: 价格={bar.close_price}, 数量={abs(self.pos)}")
                order_id = self.cover(bar.close_price, abs(self.pos))
                self.write_log(f"💰 执行买入平仓: 订单ID={order_id}")
        elif cross_below:
            self.write_log("🔴 死叉信号: 快线下穿慢线")
            if self.pos == 0:
                self.write_log(f"💰 准备卖出开仓: 价格={bar.close_price}, 数量={order_size}")
                order_id = self.short(bar.close_price, order_size)
                self.write_log(f"💰 执行卖出开仓: 订单ID={order_id}")
            elif self.pos > 0:
                self.write_log(f"💰 准备卖出平仓: 价格={bar.close_price}, 数量={self.pos}")
                order_id = self.sell(bar.close_price, self.pos)
                self.write_log(f"💰 执行卖出平仓: 订单ID={order_id}")

        self.put_event()
        
        # 更新均线值用于下一根K线判断
        self.fast_ma1 = self.fast_ma0
        self.slow_ma1 = self.slow_ma0
        
        self.write_log("✅ Bar数据处理完成")

    def on_order(self, order: OrderData) -> None:
        """
        Callback of new order data update.
        """
        self.write_log(f"📋 订单状态更新: ID={order.vt_orderid}, 合约={order.vt_symbol}, 方向={order.direction}, 价格={order.price}, 数量={order.volume}, 状态={order.status}, 已成交={order.traded}")
        
        # Check if order was rejected and log details
        if order.status == Status.REJECTED:
            self.write_log(f"❌ 订单被拒绝: {order.vt_orderid}")
            self.write_log(f"   拒绝原因可能包括:")
            self.write_log(f"   - 价格超出涨跌停板限制")
            self.write_log(f"   - 交易时间不在开市时间内")
            self.write_log(f"   - 账户资金不足")
            self.write_log(f"   - 股票停牌或有其他交易限制")

    def on_trade(self, trade: TradeData) -> None:
        """
        Callback of new trade data update.
        """
        self.write_log(f"💰 成交回报: ID={trade.vt_tradeid}, 合约={trade.vt_symbol}, 方向={trade.direction}, 价格={trade.price}, 数量={trade.volume}")
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder) -> None:
        """
        Callback of stop order update.
        """
        self.write_log(f"🛑 停止订单更新: ID={stop_order.stop_orderid}, 合约={stop_order.vt_symbol}, 方向={stop_order.direction}, 价格={stop_order.price}, 数量={stop_order.volume}, 状态={stop_order.status}")